package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.KnowledgeFoodDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.KnowledgeFood;
import com.itheima.service.KnowledgeFoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 知识库-膳食库服务实现类
 */
@Service(interfaceClass = KnowledgeFoodService.class)
@Transactional
public class KnowledgeFoodServiceImpl implements KnowledgeFoodService {
    @Autowired
    private KnowledgeFoodDao knowledgeFoodDao;

    //批量添加膳食数据
    @Override
    public void addAll(List<KnowledgeFood> knowledgeFoodList) {
        if (knowledgeFoodList != null && knowledgeFoodList.size() > 0) {
            for (KnowledgeFood knowledgeFood : knowledgeFoodList) {
                //检查此膳食数据（编码）是否存在
                long count = knowledgeFoodDao.findCountByCode(knowledgeFood.getCode());
                //如果存在，执行修改操作
                if (count > 0) {//根据膳食ID修改膳食数据
                    knowledgeFoodDao.editById(knowledgeFood);
                } else {
                    //不存在，执行添加操作
                    knowledgeFoodDao.add(knowledgeFood);
                }
            }
        }
    }

    //新增膳食库数据
    @Override
    public void add(KnowledgeFood knowledgeFood) {
        //调用DAO新增方法
        knowledgeFoodDao.add(knowledgeFood);
    }

    //分页查询膳食库数据
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        //调用分页助手
        PageHelper.startPage(currentPage, pageSize);
        //调用DAO层根据条件查询方法
        Page<KnowledgeFood> page = knowledgeFoodDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //编辑膳食数据
    @Override
    public void edit(KnowledgeFood knowledgeFood) {
        knowledgeFoodDao.editById(knowledgeFood);
    }

    //删除膳食数据
    @Override
    public void delete(Integer id) {
        knowledgeFoodDao.deleteById(id);
    }
}
